package com.bstek.pms.tools.utils;

import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.Assert;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 使用poi的api输出文档
 * @Author zhangkun
 * @CreateDate 2020/8/1
 */
public class PoiUtils {

    /**
     * 通过excel模板生成文件
     * @param exportFilePath 导出目录
     * @param param 导出内容
     * @param inputStream 模板流
     */
    public static void generateExcelFileWithModel(String exportFilePath, Map<String, Object> param, InputStream inputStream) throws Exception {
        Assert.notNull(inputStream,"未获取到模板");
        OutputStream os =  new BufferedOutputStream(new FileOutputStream(exportFilePath));
        try{
            XLSTransformer transformer = new XLSTransformer();
            Workbook workbook = transformer.transformXLS(inputStream, param);
            workbook.write(os);
        } finally {
            if(inputStream != null) inputStream.close();
            if(os != null) os.close();
        }
    }

    /**
     * 根据模板输出多sheet的Excel
     * @param exportFilePath
     * @param inputStream
     * @throws Exception
     */
    public static void generateMultipleSheetExcelWithModel(String exportFilePath,
                                                           InputStream inputStream,
                                                           List<String> sheetNames,
                                                           String beanName,
                                                           List<Map<String, Object>> sheetBeans,
                                                           int offset) throws Exception {
        Assert.notNull(inputStream,"未获取到模板");
        OutputStream os =  new BufferedOutputStream(new FileOutputStream(exportFilePath));
        try{
            XLSTransformer transformer = new XLSTransformer();
            transformer.transformMultipleSheetsList(
                    inputStream,
                    sheetBeans,
                    sheetNames,
                    beanName,
                    new HashMap<>(),
                    offset);

        } finally {
            if(inputStream != null) inputStream.close();
            if(os != null) os.close();
        }

    }

}
